package com.lvcoding.sec2.secdemo2.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @description 描述
 * @date   2022-02-28 下午6:47
 * @author  wuyanshen
 */
@Component
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    @Autowired
    public LoginFilter(@Lazy AuthenticationManager authenticationManager, LoginSuccessHandler loginSuccessHandler, LoginFailHandler loginFailHandler) {
        this.setAuthenticationManager(authenticationManager);
        this.setAuthenticationSuccessHandler(loginSuccessHandler);
        this.setAuthenticationFailureHandler(loginFailHandler);
    }

    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        String method = request.getMethod();

        if(!method.equalsIgnoreCase("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,String> map = objectMapper.readValue(request.getInputStream(), Map.class);
        String username = map.get("username");
        String password = map.get("password");

        List<GrantedAuthority> list = AuthorityUtils.createAuthorityList("cup:user:add","cup:user:update","cup:user:delete","cup:user:view");

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password, list);
        this.setDetails(request, authenticationToken);
        return this.getAuthenticationManager().authenticate(authenticationToken);
    }
}
